package com.cloud.cloudvideo.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName CheckVideoType
 * @Author AzraelJ
 * @Description 视频类型转换
 * @Date 20-5-21
 **/
@Slf4j
public class VideoTypeConvert {

    /**
     * @param /usr/bin/ffmpeg -y -i /home/jjyy/sun/volume/nginx/html/422970984207880192/source/20200528/Jx2DyETSKd/Jx2DyETSKd.avi -qscale 0 /home/jjyy/sun/volume/nginx/html/422970984207880192/source/20200528/Jx2DyETSKd/Jx2DyETSKd.mp4
     *                        ffmpeg version n4.2.2 Copyright (c) 2000-2019 the FFmpeg developers
     * @return
     * @throws Exception
     */
    public static String AviToMp4(String videoPath) throws Exception {
        File file = new File(ConfigUtil.getUploadPath()+videoPath);
        if (!file.exists()) {
            log.error("路径[" + videoPath + "]对应的视频文件不存在!");
            return "路径[" + videoPath + "]对应的视频文件不存在!";
        }

        String mp4Name = FileUtil.getPrefixOfFileName(videoPath) + ".mp4";
        String mp4Path = file.getParent();
        //ffmpeg -i FILE_NAME.wmv -qscale 0 NEW_FILE_NAME.mp4
        List<String> command = new java.util.ArrayList<>();
        command.add(ConfigUtil.getFfmpeg());
//        command.add("ffmpeg");
//        command.add("D:\\ffmpeg\\ffmpeg-N-99502-g0d156eb58a-win64-gpl\\bin\\ffmpeg.exe");
        command.add("-y");
        command.add("-i");
        command.add(ConfigUtil.getUploadPath()+videoPath.replace("/","\\"));
        command.add("-qscale");
        command.add("0");
        command.add(mp4Path + "\\" + mp4Name);

        try {
            log.info("ffmpeg视频转码命令：" + listToString5(command, ' '));
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(command);
            Process p = builder.start();
            doWaitFor(p);
            p.destroy();
            return videoPath.substring(0,videoPath.lastIndexOf("."))+".mp4";
        }
        catch (Exception e) {
            log.info("wmv视频转码失败", e);
            e.printStackTrace();
            throw new Exception("wmv视频转码失败");
        }
    }
    
    
    public static String listToString5(List list, char separator) {
        return StringUtils.join(list.toArray(), separator);
    }

    public static int doWaitFor(Process p) {
        InputStream in = null;
        InputStream err = null;
        int exitValue = -1; // returned to caller when p is finished
        try {
            System.out.println("comeing");
            in = p.getInputStream();
            err = p.getErrorStream();
            boolean finished = false; // Set to true when p is finished

            while (!finished) {
                try {
                    while (in.available() > 0) {
                        Character c = new Character((char) in.read());
                        System.out.print(c);
                    }
                    while (err.available() > 0) {
                        Character c = new Character((char) err.read());
                        System.out.print(c);
                    }

                    exitValue = p.exitValue();
                    finished = true;

                }
                catch (IllegalThreadStateException e) {
                    Thread.currentThread().sleep(500);
                }
            }
        }
        catch (Exception e) {
            System.err.println("doWaitFor();: unexpected exception - " + e.getMessage());
        }
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            }
            catch (IOException e) {
                System.out.println(e.getMessage());
            }
            if (err != null) {
                try {
                    err.close();
                }
                catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return exitValue;
    }

    public static String toMp4(String videoPath) throws Exception {
        File file = new File(videoPath);
        if (!file.exists()) {
            log.error("路径[" + videoPath + "]对应的视频文件不存在!");
            return "路径[" + videoPath + "]对应的视频文件不存在!";
        }

        String mp4Name = FileUtil.getPrefixOfFileName(videoPath) + ".mp4";
        String mp4Path = file.getParent();
        //ffmpeg -i FILE_NAME.wmv -qscale 0 NEW_FILE_NAME.mp4
        List<String> command = new java.util.ArrayList<>();
        command.add(ConfigUtil.getFfmpeg());
        command.add("-y");
        command.add("-i");
        command.add(videoPath);
        command.add("-c:v");
        command.add("libx264");
        command.add("-mbd");
        command.add("0");
        command.add("-c:a");
        command.add("aac");
        command.add("-strict");
        command.add("-2");
        command.add("-pix_fmt");
        command.add("yuv420p");
        command.add("-movflags");
        command.add("faststart");
        command.add(mp4Path + "/" + mp4Name);

        try {
            log.info("ffmpeg视频转码命令：" + listToString5(command, ' '));
            Process videoProcess = new ProcessBuilder(command).redirectErrorStream(true).start();
//            new PrintStream(videoProcess.getErrorStream()).start();
//            new PrintStream(videoProcess.getInputStream()).start();
            videoProcess.waitFor();
            return mp4Path + "/" + mp4Name;
        }
        catch (Exception e) {
            log.info(listToString5(command, ' ') + " flv、wmv视频转码失败", e);
            e.printStackTrace();
            throw new Exception("flv、wmv视频转码失败");
        }
    }
}


